package com.atguigu.chapter07.D02_WaterMark;

import com.atguigu.bean.WaterSensor;
import com.atguigu.util.AnqclnUtil;
import org.apache.flink.api.common.eventtime.*;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.List;

/**
 * Author: Pepsi
 * Date: 2023/8/5
 * Desc:
 *
 * 进入哪个窗口看事件事件
 * 窗口啥时候关闭看水印 [)  前闭后开
 *
 * 水印可以解决数据的乱序问题
 *
 */
public class Flink03_WaterMark_morePar {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port",1000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);

        //将并行度设置为2，查看多并行度下水印的传递问题   以最小的那个为准
        env.setParallelism(2);

        // 设置水印生成的周期   水印两秒生成一次
        env.getConfig().setAutoWatermarkInterval(2000);

        env
                .socketTextStream("hadoop101",9999)
                .map(line->{
                    String[] data = line.split(",");
                    return new WaterSensor(
                            data[0],
                            Long.valueOf(data[1]),
                            Integer.valueOf(data[2])
                    );
                })
                // 加水印  分配时间戳和水印
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                        // 指明时间戳怎么来
                        .withTimestampAssigner(new SerializableTimestampAssigner<WaterSensor>() {
                            @Override
                            public long extractTimestamp(WaterSensor element, long recordTimestamp) {
                                return element.getTs();
                            }
                        })
                        .withIdleness(Duration.ofSeconds(5))  //解决数据倾斜导致的水印不更新问题，如果某个并行度水印超过5s没有更新，则以其他的为准
                )
                .keyBy(WaterSensor::getId)
                //  用滚动的事件窗口
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                .process(new ProcessWindowFunction<WaterSensor, String, String, TimeWindow>() {
                    @Override
                    public void process(String s, Context context, Iterable<WaterSensor> elements, Collector<String> out) throws Exception {
                        List<WaterSensor> list = AnqclnUtil.toList(elements);
                        String startTime = AnqclnUtil.toDateTime(context.window().getStart());
                        String endTime = AnqclnUtil.toDateTime(context.window().getEnd());
                        out.collect(s+" "+startTime+" "+endTime+" "+list);
                    }
                })
                .print();

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
